<template>
  <div style="z-index: 999">
    <el-dialog
      :visible.sync="trajectoryShow"
      :title="toTraCode + '车辆轨迹'"
      width="50%"
      center
      @close="closeDialog"
    >
      <div class="dialog-content">
        <div class="mapbox">
          <div id="tramap" style="height: 400px; width: 100%"></div>

          <div class="btnBox">
            <div @click="start()" class="btn">开始</div>
            <div @click="pause()" class="btn">暂停</div>
            <div @click="resume()" class="btn" v-if="this.mapType == 'GMAP'">
              继续
            </div>
            <div @click="stop()" class="btn">停止</div>
          </div>
        </div>

        <div class="content">
          <!-- <div>
            <el-button type="primary">轨迹查询</el-button>
            <el-button type="primary">导出</el-button>
          </div> -->

          <div class="searchbox">
            <div>
              <span style="margin-right: 20px">
                总条数：{{ loactionList.length }}
              </span>
              <el-date-picker
                v-model="dateTime"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                size="mini"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
              >
              </el-date-picker>

              <el-button
                type="primary"
                @click="getlist"
                size="mini"
                class="searchBtn"
                >搜索</el-button
              >
              <el-button @click="exportTable" size="mini">导出</el-button>
            </div>
          </div>

          <el-table
            ref="table"
            :data="loactionList"
            :header-cell-style="{
              background: '#f2f2f2',
              color: '#333',
              fontSize: '12px',
            }"
            size="mini"
            height="260px"
          >
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
            >
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="gpsTime"
              label="时间"
              align="center"
              width="150"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.gpsTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="speed" label="速度" align="center" width="">
            </el-table-column>
            <el-table-column
              prop="direction"
              label="方向"
              align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column
              prop="mileage"
              label="里程"
              align="center"
              width=""
            >
            </el-table-column>
            <el-table-column prop="lng" label="经度" align="center" width="100">
            </el-table-column>
            <el-table-column prop="lat" label="纬度" align="center" width="100">
            </el-table-column>
            <el-table-column
              prop="curAddress"
              label="位置"
              align="center"
              width="500"
            >
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script
type="text/javascript"
src="https://gis.soszyzg.com/tdtapi?v=4.0&tk=33752fcceac2cec91dcd788b342fba06"
></script>
<script src="https://gis.soszyzg.com/tdtlbsjs/lib/d3/d3.min.js" charset="utf-8"></script>
<script src="https://gis.soszyzg.com/tdtlbsapi/js4.0/opensource/openlibrary/D3SvgOverlay.js"></script>
<script src="https://gis.soszyzg.com/tdtlbsapi/js4.0/opensource/openlibrary/CarTrack.js"></script>
<script src="https://gis.soszyzg.com/tdtlbsapi/js4.0/opensource/data/point.js"></script>

   <!-- <script src="http://lbs.tianditu.gov.cn/js/lib/d3/d3.min.js" charset="utf-8"></script> -->
	<!-- <script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/D3SvgOverlay.js"></script> -->
	<!-- <script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/CarTrack.js"></script> -->
	<!-- <script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/data/point.js"></script> -->
 

<script>
import api from "../../../api/location/positioning";

export default {
  props: {
    toTraCode: "",
  },
  data() {
    return {
      trajectoryShow: false,
      loactionList: [],
      dateTime: [],
      mapType: "",
    };
  },
  watch: {},
  mounted() {
    this.getCurrentTime();
    // this.initmap();
  },

  methods: {
    getCurrentTime() {
      //获取当前时间
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      let gettime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      let starttime = yy + "-" + mm + "-" + dd + " 00:00:00";
      this.dateTime.push(starttime, gettime);
    },
    // 初始化高德地图
    initmap() {
      console.log("==22=======ssss");

      this.map = new AMap.Map("tramap", {
        //设置地图容器id
        viewMode: "3D", //是否为3D地图模式
        zoom: 13, //初始化地图级别
        center: [104.10194, 30.65984], //初始化地图中心点位置
      });

      let toolBar = new AMap.ToolBar({
        position: {
          top: "110px",
          right: "40px",
        },
      });
      let controlBar = new AMap.ControlBar({
        position: {
          top: "10px",
          right: "10px",
        },
      });
      this.map.addControl(new AMap.Scale());
      this.map.addControl(toolBar);
      this.map.addControl(controlBar);
      this.map.setDefaultCursor("pointer");

      // this.setClusterMraker();
      // this.setMapline();
    },
    // 初始化天地图
    initTMap(val) {
      console.log("initTMap==");
      var tile = new T.TileLayer(
        "https://gis.soszyzg.com/tdtDataServer?T=vec_w&x={x}&y={y}&l={z}&tk=33752fcceac2cec91dcd788b342fba06"
      );
      this.tmap = new T.Map("tramap", { layers: [tile] });
      this.tmap.centerAndZoom(new T.LngLat(104.087715, 30.567811), 12);
      this.tmap.enableScrollWheelZoom(true);
    },
    setMapline(val = []) {
      this.marker = new AMap.Marker({
        map: this.map,
        position: val ? val[0] : [104.10194, 30.65984],
        icon: "http://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
        offset: new AMap.Pixel(-13, -26),
      });

      this.lineArr = [
        [104.10194, 30.65984],
        [104.1018, 30.65975],
        [104.1017, 30.65972],
        [104.1017, 30.65965],
        [104.1015, 30.6596],
        [104.1014, 30.65954],
        [104.1013, 30.65932],
        [104.1012, 30.659802],
      ];
      this.lineArr = val;

      // 绘制轨迹
      this.polyline = new AMap.Polyline({
        map: this.map,
        path: this.lineArr,
        showDir: true,
        strokeColor: "#28F", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6, //线宽
        // strokeStyle: "solid"  //线样式
      });

      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        strokeColor: "#AF5", //线颜色
        strokeWeight: 6, //线宽
      });

      this.marker.on("moving", (e) => {
        this.passedPolyline.setPath(e.passedPath);
        this.map.setCenter(e.target.getPosition(), true);
      });
      this.map.setFitView();
    },
    TmapSetMapline(val) {
      let that = this;
      // 移动到中心点
      that.tmap.centerAndZoom(new T.LngLat(val[0][0], val[0][1]), 18);

      //创建标注对象
      let startPoint = new T.LngLat(val[0][0], val[0][1]);
      let endPoint = new T.LngLat(
        val[val.length - 1][0],
        val[val.length - 1][1]
      );
      // 起点
      const startMarker = new T.Marker(startPoint, {
        icon: new T.Icon({
          iconUrl: "https://gis.soszyzg.com/tdtimages/bus/start.png",
          iconAnchor: new T.Point(12, 31),
        }),
      });
      // 终点
      const endMarker = new T.Marker(endPoint, {
        icon: new T.Icon({
          iconUrl: "http://lbs.tianditu.gov.cn/images/bus/end.png",
          iconAnchor: new T.Point(12, 31),
        }),
      });
      //向地图上添加标注
      that.tmap.addOverLay(startMarker);
      that.tmap.addOverLay(endMarker);

      let points = [];
      val.forEach((item) => {
        points.push(new T.LngLat(item[0], item[1], item.curAddress));
      });
      // console.log(1231, points);
      setTimeout(() => {
        //创建线对象
        var line = new T.Polyline(points);
        //向地图上添加线
        that.tmap.addOverLay(line);
      }, 1000);
    },
    TmapSetTravel(val) {
      console.log("轨迹start", val);
      // 轨迹点列表
      var pointList = [
        {
          // time: "2023-12-19 10:28:10",
          lng: 121.1342347,
          lat: 32.0551446,
        },
        {
          // time: "2023-12-19 10:28:30",
          lng: 121.1406307,
          lat: 32.0553588,
        },
        {
          time: "2023-12-19 10:29:10",
          lng: 121.1475297,
          lat: 32.0555119,
        },
        {
          time: "2023-12-19 10:29:30",
          lng: 121.1579859,
          lat: 32.0558791,
        },
        {
          time: "2023-12-19 10:29:50",
          lng: 121.1679751,
          lat: 32.0563687,
        },
        {
          time: "2023-12-19 10:30:10",
          lng: 121.1820965,
          lat: 32.0571032,
        },
        {
          time: "2023-12-19 10:30:20",
          lng: 121.1866958,
          lat: 32.0572256,
        },
        {
          time: "2023-12-19 10:30:30",
          lng: 121.1869832,
          lat: 32.0557261,
        },
        {
          time: "2023-12-19 10:30:40",
          lng: 121.1869473,
          lat: 32.0534614,
        },
        {
          time: "2023-12-19 10:31:10",
          lng: 121.1835337,
          lat: 32.0486566,
        },
      ];
      pointList = val;
      this.tmap.centerAndZoom(
        new T.LngLat(pointList[0].lng, pointList[0].lat),
        14
      );
      // 创建车辆轨迹
      this.CarTrack = new T.CarTrack(this.tmap, {
        interval: 5,
        speed: 10,
        dynamicLine: true,
        polylinestyle: { color: "#2C64A7", weight: 5, opacity: 0.9 },
        carstyle: {
          display: true,
          iconUrl: require("@/assets/images/car.png"),
          width: 52,
          height: 26,
        },
        Datas: pointList.map(function (obj, i) {
          var lonLat = new T.LngLat(obj.lng, obj.lat);
          return lonLat;
        }),
        passOneNode: this.passOneNode, //车辆移动一次时触发调用的方法
      });
    },
    //车辆移动一次时触发调用的方法 Lnglat：经过的坐标 index：节点序号。
    passOneNode(Lnglat) {
      this.tmap.panTo(new T.LngLat(Lnglat.lng, Lnglat.lat));
    },

    getlist() {
      let obj = {
        configId: this.configId,
        startTime: this.dateTime[0],
        endTime: this.dateTime[1],
      };
      this.exportData = obj;
      console.log(obj);

      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      api
        .trackData(obj)
        .then((res) => {
          loading.close();
          console.log("========>res", res);
          if ((res.code = 200)) {
            let data = res.data;
            this.loactionList = data;
            this.getline(data);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          loading.close();
        });
    },
    getline(data) {
      let arr = [];
      // console.log(this.mapType, "=======<");
      this.trackStatus = "";
      if (this.mapType == "GMAP") {
        arr = data.map((item) => {
          return [item.gdLng, item.gdLat];
        });
        // console.log(arr, "==GMAParr=");

        if (arr.length != 0) {
          this.setMapline(arr);
        } else {
          this.$message.warning("暂无轨迹数据");
        }
      } else if (this.mapType == "TMAP") {
        arr = data.map((item) => {
          // return [item.lng, item.lat];
          return { lng: item.lng, lat: item.lat };
        });
        // console.log(arr, "==TMAParr=");
        if (arr.length != 0) {
          // this.TmapSetMapline(arr);
          this.TmapSetTravel(arr);
        } else {
          this.$message.warning("暂无轨迹数据");
        }
      }
    },
    // 开始
    start() {
      if (this.trackStatus == "START") {
        this.$message.warning("已开始行程");
        return false;
      }

      this.$message.success("开始行程");
      if (this.mapType == "TMAP") {
        this.CarTrack.start();
      } else if (this.mapType == "GMAP") {
        this.marker.moveAlong(this.lineArr, {
          // 每一段的时长
          duration: 400, //可根据实际采集时间间隔设置
          // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
          autoRotation: true,
        });
      }
      this.trackStatus = "START";
    },
    // 暂停
    pause() {
      if (this.trackStatus == "PAUSE_MOVE") {
        this.$message.warning("已暂停行程");
        return false;
      }

      this.$message.success("暂停行程");
      if (this.mapType == "TMAP") {
        this.CarTrack.pause();
      } else if (this.mapType == "GMAP") {
        this.marker.pauseMove();
      }
      this.trackStatus = "PAUSE_MOVE";
    },
    // 继续
    resume() {
      if (this.trackStatus == "START" || this.trackStatus == "RESUME_MOVE") {
        this.$message.warning("正在行程中");
        return false;
      }
      this.$message.success("继续行程");
      this.marker.resumeMove();
      this.trackStatus = "RESUME_MOVE";
    },
    // 停止
    stop() {
      this.$message.success("停止行程");
      if (this.mapType == "TMAP") {
        this.CarTrack.stop();
      } else if (this.mapType == "GMAP") {
        this.marker.stopMove();
      }
      this.trackStatus = "STOP_MOVE";
    },
    show(val) {
      this.trajectoryShow = val.show;
      this.configId = val.configId;
      this.loactionList = [];
      this.$nextTick(() => {
        if (val.mapType === "GMAP") {
          this.mapType = "GMAP";
          this.initmap(val);
        } else if (val.mapType === "TMAP") {
          this.mapType = "TMAP";
          this.initTMap(val);
        }
      });
    },
    carBrandCheckval() {
      this.trajectoryShow = false;
    },
    // 导出
    exportTable() {
      let params = {
        configId: this.configId,
        startTime: this.dateTime[0],
        endTime: this.dateTime[1],
      };
      this.download(
        "/location/track/trackData/export",
        {
          ...params,
        },
        `车辆历史轨迹_${new Date().getTime()}.xlsx`
      );
    },
    closeDialog() {
      if (this.mapType == "TMAP") {
        this.CarTrack.stop();
      } else if (this.mapType == "GMAP") {
        this.marker.stopMove();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-content {
  z-index: 999;
  .mapbox {
    position: relative;
    .btnBox {
      position: absolute;
      right: 60px;
      bottom: 20px;
      z-index: 999;
      padding: 4px 18px;
      display: flex;
      .btn {
        background: #409eff;
        color: #fff;
        font-size: 12px;
        width: 60px;
        height: 30px;
        margin-right: 10px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .content {
    height: 300px;
  }
}
::v-deep .el-dialog__body {
  padding: 0;
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.searchbox {
  font-size: 14px;
  margin: 5px 16px 10px 16px;
  .searchBtn {
    margin: 0 6px;
  }
}
</style>
